package com.ai.service.impl;

import org.springframework.ai.document.Document;
import org.springframework.ai.reader.tika.TikaDocumentReader;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/*
 * MetadataService 元数据处理服务
 * TikaDocumentReader 不仅能提取内容，还能提取文档的元数据（Metadata），如作者、标题、创建日期等
 */
@Service
public class MetadataService {

    /**
     * 提取文件元数据
     * @param filePath String
     */
    public void extractMetadata(String filePath) {
        TikaDocumentReader reader = new TikaDocumentReader(new FileSystemResource(filePath));
        List<Document> documents = reader.get();

        if (!documents.isEmpty()) {
            Document firstDoc = documents.getFirst();
            String content = firstDoc.getText();
            Map<String, Object> metadata = firstDoc.getMetadata();

            System.out.println("内容长度: " + content.length());
            System.out.println("元数据:");
            for (Map.Entry<String, Object> entry : metadata.entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }
        }
    }

    /**
     * 提取上传文件的元数据
     * @param file 上传的文件
     * @return 元数据映射
     */
    public Map<String, Object> extractMetadata(MultipartFile file) {
        try {
            Resource resource = new InputStreamResource(file.getInputStream());
            TikaDocumentReader reader = new TikaDocumentReader(resource);
            List<Document> documents = reader.get();

            if (!documents.isEmpty()) {
                return documents.getFirst().getMetadata();
            }
            return Map.of();
        } catch (IOException e) {
            throw new RuntimeException("元数据提取失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取文件内容和元数据的完整信息
     * @param file 上传的文件
     * @return 包含内容和元数据的字符串
     */
    public String getFileInfoWithMetadata(MultipartFile file) {
        try {
            Resource resource = new InputStreamResource(file.getInputStream());
            TikaDocumentReader reader = new TikaDocumentReader(resource);
            List<Document> documents = reader.get();

            if (documents.isEmpty()) {
                return "未提取到任何内容";
            }

            Document firstDoc = documents.getFirst();
            StringBuilder info = new StringBuilder();
            assert firstDoc.getText() != null;
            info.append("内容预览: ").append(firstDoc.getText(), 0, Math.min(200, firstDoc.getText().length())).append("...\n");
            info.append("元数据:\n");

            for (Map.Entry<String, Object> entry : firstDoc.getMetadata().entrySet()) {
                info.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
            }

            return info.toString();
        } catch (IOException e) {
            throw new RuntimeException("文件信息获取失败: " + e.getMessage(), e);
        }
    }
}
